package cn.edu.hit.core.message;

import cn.edu.hit.HttpRequestor;
import cn.edu.hit.HttpRequestorWithTokenForJoinsystem;
import cn.edu.hit.core.Document;
import cn.edu.hit.core.conf.ConfigureLoader;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 获取钧安世通历史快数据
 * 使用历史数据接口，对每一项生成一个Map key--timestamp value--signalValue
 */
public final class JoinSystemFastAdapter2 extends MessageAdapterHelper2<JSONArray> {
    @Override
    public boolean accept(String type) {
        return "JoinSystemFast2".equalsIgnoreCase(type);
    }

    private HttpRequestorWithTokenForJoinsystem requestor;
    private String token_aquire_url;
    private String token_aquire_user;
    private String token_aquire_password;
    private String feature_aquire_url;

    private static String urlString = "http://172.16.45.244:8093/rsapi/historyData/points/";
    private long work_span = 10000;

    {
        Document conf = ConfigureLoader.getInstance().getBaseConfigure();
        urlString = conf.getString("JOINSYSTEM_GET_URL2", "http://172.16.45.244:8093/rsapi/historyData/points/");
        String WORK_SPAN = conf.getString("WORK_SPAN", "10000");

        token_aquire_url = conf.getString("token_aquire_url", token_aquire_url);
        token_aquire_user = conf.getString("token_aquire_user", token_aquire_user);
        token_aquire_password = conf.getString("token_aquire_password", token_aquire_password);
        feature_aquire_url = conf.getString("feature_aquire_url", feature_aquire_url);
        requestor = HttpRequestorWithTokenForJoinsystem.getInstance(token_aquire_url, token_aquire_user, token_aquire_password);
        try {
            work_span = Integer.parseInt(WORK_SPAN);
            if (work_span <= 500) {
                work_span = 500;
            }
        } catch (NumberFormatException ex) {
            System.err.println("配置文件不正确，" + WORK_SPAN + "应当为大于500的整数。 ");
        }
    }

    @Override
    protected JSONArray pretreat(Long timestamp) {
        List<String> jsIds = configureMap.entrySet().parallelStream().map(entry -> {
            Document configure = (Document) entry.getValue();
            return configure.getString(DATA_SOURCE_ARGS);
        }).collect(Collectors.toList());

        if (jsIds.size() == 0)
            return new JSONArray();

        try {
            return requestAsJson(jsIds, timestamp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JSONArray();
    }

    @Override
    protected Object getValue(JSONArray data, String id, Document configure) {
        String joinSystemId = configure.getString(DATA_SOURCE_ARGS);
        Map<Long, List<Double>> resultMap = new ConcurrentHashMap<>();
        data.stream()//.<JSONObject>map(x-> ((JSONObject) x))
                .filter(json -> joinSystemId.equals(((JSONObject) json).optString("pointId")))
                .forEach(json -> {
                    JSONObject jsonObject = (JSONObject) json;
                    long timestamp = jsonObject.optLong("pointTime");
                    List<Double> values;
                    String valueString = jsonObject.getString("waveValues");
                    if ("-".equals(valueString)) {
                        values = Collections.emptyList();
                    } else {
                        values = Arrays.stream(valueString.split(","))
                                .mapToDouble(Double::parseDouble).boxed()
                                .collect(Collectors.toList());
                    }
                    resultMap.put(timestamp, values);
                });
        return resultMap;
    }

    private JSONArray requestAsJson(List<String> jsIds, Long timestamp) throws Exception {
        String url = String.format(urlString + String.join(",", jsIds) + "/times?beginTime=%d&endTime=%d", timestamp - work_span, timestamp);
        String resultJson = requestor.doGet(url);
        System.out.println(resultJson);
        JSONObject jsonObject = JSONObject.fromObject(resultJson);
        return jsonObject.getJSONArray("data");
    }
}
